package com.vieewer.btdemo.view.compass;

import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.animation.Animation;
import android.view.animation.RotateAnimation;
import android.widget.ImageView;
import android.widget.TextView;
import com.alibaba.fastjson.JSON;
import com.vieewer.btdemo.R;
import com.vieewer.btdemo.bean.DegreeBean;
import com.vieewer.btdemo.bean.SwitchBean;
import com.vieewer.btdemo.utils.CommunicateToPhoneHelper;
import com.vieewer.btdemo.utils.LogUtil;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

public class CompassManager implements SensorEventListener {

    private SensorManager sensorManager;
    private float lastRotateDegree;
    // 记录指南针图片转过的角度
    float currentDegree = 0f;
    float degree;
    float lastDegree = -1;

    private String mSwitchType = "off";

    private long lastTimeMillis = 0;


    private CompassManager() {

    }

    public void setSwitchBtn(boolean b) {
        if (b) {
            mSwitchType = "on";
        } else {
            mSwitchType = "off";
        }
    }

    private static class Instance {
        public static CompassManager singletonState = new CompassManager();
    }

    public static CompassManager getNewInstance() {
        return Instance.singletonState;
    }


    public void init(Context context) {

        EventBus.getDefault().register(this);
        sensorManager = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE);

        //加速度感应器
        Sensor magneticSensor = sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
        //地磁感应器
        Sensor accelerometerSensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);

        // 为系统的方向传感器注册监听器
        sensorManager.registerListener(this,
                sensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION),
                SensorManager.SENSOR_DELAY_GAME);
    }



    public void unregister() {

        if (sensorManager != null) {
            sensorManager.unregisterListener(this);
        }

        EventBus.getDefault().unregister(this);
    }


    float[] accelerometerValues = new float[3];

    float[] magneticValues = new float[3];

    @Override
    public void onSensorChanged(SensorEvent event) {

        // 获取触发event的传感器类型
        int sensorType = event.sensor.getType();
        if (sensorType == Sensor.TYPE_ORIENTATION) {
            // 获取绕Z轴转过的角度
            degree = event.values[0];//0表示北（North）；90表示东（East）；180表示南（South）；270表示西（West）
/*            if(degree>0&& degree<45) degree= (float) 22.5;
            else if(degree>45&& degree<90) degree= (float) 67.5;
            else if(degree>90&& degree<135) degree= (float) 112.5;
            else if(degree>135&& degree<180) degree= (float) 157.5;
            else if(degree>180&& degree<225) degree= (float) 202.5;
            else if(degree>225&& degree<270) degree= (float) 247.5;
            else if(degree>270&& degree<315) degree= (float) 292.5;
            else if(degree>315&& degree<360) degree= (float) 337.5;*/

            //txt_compass_direction.setText(degree + "");


            long differ = System.currentTimeMillis() - lastTimeMillis;


            if (mSwitchType.equals("on") && lastDegree != degree && differ > 20*1000) {
                Log.i("yjj", "degree = " + degree + ", timemillis >>>" + differ);
                DegreeBean data = new DegreeBean();
                data.type = "degree";
                data.degree = degree;
                String dataStr = JSON.toJSONString(data);
                LogUtil.e("yjj", dataStr);
                CommunicateToPhoneHelper.Companion.getInstance().write(dataStr);

                lastTimeMillis = System.currentTimeMillis();
                lastDegree = degree;

            } else if (mSwitchType.equals("off")) {


            }


            // 创建旋转动画（反向转过degree度）
            RotateAnimation ra = new RotateAnimation(currentDegree, -degree,
                    Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
            // 设置动画的持续时间
            ra.setDuration(200);
            // 运行动画
//            compassImage.startAnimation(ra);
            currentDegree = -degree;


        }

    }


    //处理事件逻辑
    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onEventBus(SwitchBean bean) {

        if (bean != null) {

            Log.i("yjj", "CompassActivity receive msg from phone ~~~" + ", is on =" + bean.getIsOn());

            mSwitchType = bean.getIsOn();
        }

    }



    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {

    }
}

